package com.atguigu.gmall.realtime.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.util.List;

/**
 * @author Archie
 * @date 2021-10-21 16:02
 * @description
 */
public class DimUtil {
	public static JSONObject getDimFromPhoenix(Connection phoenixConn, String tableName, Long id) {
		String sql = "select * from " + tableName + " where id=?";
		String[] args = {id.toString()};
		List<JSONObject> list = JDBCUtil.queryList(phoenixConn, sql, args, JSONObject.class);
		return list.size() == 0 ? null : list.get(0);
	}

	// 从redis读取维度数据
	private static JSONObject getDimFromRedis(Jedis redisClient, String tableName, Long id) {
		String key = tableName + ":" + id;

		String dimString = redisClient.get(key);

		if (dimString != null) {
			// 更新过期时间
			redisClient.expire(key, 2 * 24 * 60 * 60);
			return JSON.parseObject(dimString);
		}

		return null;
	}

	// 把维度写入到redis
	private static void writeDimToRedis(Jedis redisClient, String tableName, Long id, JSONObject dim) {
		String key = tableName + ":" + id;
		String value = dim.toJSONString();

        /*redisClient.set(key, value);
        redisClient.expire(key, 2 * 24 * 60 * 60); // 设置过期时间*/

		redisClient.setex(key, 2 * 24 * 60 * 60, value);
	}

	public static JSONObject getDim(Jedis redisClient,
									Connection phoenixConn,
									String tableName,
									Long id) {

		// 1. 先去redis读取缓存, 如果读到, 则直接返回数据
		JSONObject dim = getDimFromRedis(redisClient, tableName, id);
		if (dim == null) {
			System.out.println(tableName + "  " + id + " 走数据库");
			// 2. 如果读不到, 再去Phoenix查询
			dim = getDimFromPhoenix(phoenixConn, tableName, id);
			// 3. 把缓存写入到redis
			writeDimToRedis(redisClient, tableName, id, dim);
		} else {
			System.out.println(tableName + "  " + id + " 走缓存");
		}
		return dim;
	}

}
